package com.example.hrandroidapp.preferences;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.example.hrandroidapp.domain.ServerPO;
import com.google.gson.Gson;

public class ServerListPreference {
	
	private static final String SERVER_LIST_PREF_NAME = "SERVER_LST_APP";
	private static final String SERVERS = "SERVER_LST";
	
	public ServerListPreference() {
	}
	
	public static void saveServers(Context context, List<ServerPO> Servers) {
        SharedPreferences settings;
        Editor editor;
 
        settings = context.getSharedPreferences(SERVER_LIST_PREF_NAME, Context.MODE_PRIVATE);
        editor = settings.edit();
 
        Gson gson = new Gson();
        String jsonServers = gson.toJson(Servers);
 
        editor.putString(SERVERS, jsonServers);
 
        editor.commit();
    }
 
    public static void addServers(Context context, ServerPO ServerPO) {
        List<ServerPO> Servers = getServers(context);
        if (Servers == null)
            Servers = new ArrayList<ServerPO>();
        Servers.add(ServerPO);
        saveServers(context, Servers);
    }
 
    public static void removeFavorite(Context context, ServerPO ServerPO) {
        ArrayList<ServerPO> Servers = getServers(context);
        if (Servers != null) {
            Servers.remove(ServerPO);
            saveServers(context, Servers);
        }
    }
 
    public static ArrayList<ServerPO> getServers(Context context) {
        SharedPreferences settings;
        List<ServerPO> Servers = new ArrayList<ServerPO>();
 
        settings = context.getSharedPreferences(SERVER_LIST_PREF_NAME, Context.MODE_PRIVATE);
 
        if (settings.contains(SERVERS)) {
            String jsonServers = settings.getString(SERVERS, null);
            Gson gson = new Gson();
            ServerPO[] serverPO = gson.fromJson(jsonServers, ServerPO[].class);
 
            Servers = Arrays.asList(serverPO);
            Servers = new ArrayList<ServerPO>(Servers);
        } else
            return null;
 
        return (ArrayList<ServerPO>) Servers;
    }
}
